#include "ship.h"

#include <exception>

using namespace std;
//REMOVE ^ once ship components are in

//STUPID LINKING ERROR FIX FROM: physicsable.h
std::map<PhysicsType, std::map<PhysicsType, bool> > Physicsable::collisionMap_;
cpSpace* Physicsable::space_;
std::map<cpShape*, Physicsable*> Physicsable::shapeMap_;

void Ship::draw() {	
	float direction = (getBody()->a)* rToDeg;
	float x = getBody()->p.x;
	float y = getBody()->p.y;

	glTranslatef(x, y, 0.0);
	glRotatef(direction, 0.0, 0.0, 1.0);

	glColor4f(r, g, b, 1.0);
	
	glBegin(GL_POLYGON); {
		for (int i = 0; i < numVertii_; i++) {
			glVertex2f(vertii_[i].x, vertii_[i].y);
		}
	} 
	glEnd();
	
	glColor4f(cR, cG, cB, 1.0);

	glBegin(GL_POLYGON); {
		for (int i = 0; i < numBridgeVertii_; i++) {
			glVertex2f(bridgeVertii_[i].x, bridgeVertii_[i].y);
		}
	} 
	glEnd();

	list<Component*>::iterator ci;

	for(ci = components_.begin(); ci != components_.end(); ci++) {
		if((*ci)->isDrawable()) {
			(*ci)->draw();
		}
	}

	glRotatef(-direction, 0.0, 0.0, 1.0);
	glTranslatef(-x, -y, 0.0);
}

void Ship::update(float step) {
	list<Component*>::iterator ci;

	for(ci = components_.begin(); ci != components_.end(); ci++) {
		if((*ci)->isUpdateable()) {
			(*ci)->update(step);
		}
	}
}

void Ship::respond(ButtonPress button) {
	list<Component*>* cList;
	list<Component*>::iterator ci;
	
	if(keyBinds_[button.getButton()] != NULL) {
		cList = keyBinds_[button.getButton()];
		if(button.getDown()) {
			for(ci = cList->begin(); ci != cList->end(); ci++) {
				(*ci)->activate();
			}
		} else if(!button.getDown()) {
			for(ci = cList->begin(); ci != cList->end(); ci++) {
				(*ci)->deactivate();
			}
		}
	} else {
		keyBinds_.erase(button.getButton());
	}
}
